$(document).ready(function() {
    // 检查认证状态
    if (!utils.checkAuth()) return;
    
    // 显示用户信息
    const userInfo = JSON.parse(localStorage.getItem(STORAGE_KEYS.USER_INFO));
    $('#userName').text(`${userInfo.name}（管理员）`);
    
    // 加载统计数据
    loadStatistics();
    
    // 加载学生列表
    loadStudents();
    
    // 加载课程列表
    loadCourses();
    
    // 加载班级列表
    loadClasses();
    
    // 加载选课记录
    loadEnrollments();
    
    // 添加选课记录模态框显示时加载数据
    $('#addStudentClassModal').on('show.bs.modal', function() {
        loadStudentOptions();
        loadClassOptions();
    });
    
    // 统一处理所有表单提交
    const forms = {
        '#addStudentForm': {
            url: '/students',
            getData: () => ({
                student_id: $('#studentId').val(),
                name: $('#studentName').val(),
                major: $('#studentMajor').val(),
                password: $('#studentPassword').val()
            }),
            messageEl: '#addStudentMessage',
            modalId: 'addStudentModal',
            reload: () => { loadStudents(); loadStatistics(); }
        },
        '#addCourseForm': {
            url: '/courses',
            getData: () => ({
                course_id: $('#courseId').val(),
                name: $('#courseName').val(),
                credit: parseInt($('#courseCredit').val())
            }),
            messageEl: '#addCourseMessage',
            modalId: 'addCourseModal',
            reload: () => { loadCourses(); loadStatistics(); }
        },
        '#addClassForm': {
            url: '/classes',
            getData: () => ({
                course_id: $('#classCourseId').val(),
                teacher_id: $('#classTeacherId').val(),
                semester: $('#classSemester').val(),
                time_location: $('#classTimeLocation').val()
            }),
            messageEl: '#addClassMessage',
            modalId: 'addClassModal',
            reload: () => { loadClasses(); loadStatistics(); }
        },
        '#addStudentClassForm': {
            url: '/student-class',
            getData: () => ({
                student_id: $('#scStudentId').val(),
                class_id: parseInt($('#scClassId').val())
            }),
            messageEl: '#addStudentClassMessage',
            modalId: 'addStudentClassModal',
            reload: () => { loadClasses(); loadEnrollments(); }
        }
    };
    
    // 绑定所有表单提交事件
    Object.entries(forms).forEach(([selector, config]) => {
        $(selector).on('submit', function(e) {
            e.preventDefault();
            
            $.ajax({
                url: getFullApiPath(ROLE_API_PATHS[3], config.url),
                type: 'POST',
                headers: utils.getAuthHeader(),
                contentType: 'application/json',
                data: JSON.stringify(config.getData()),
                success: function(response) {
                    const result = utils.handleApiResponse(response);
                    if (result.success) {
                        utils.showMessage($(config.messageEl), '操作成功！', 'success');
                        $(selector)[0].reset();
                        config.reload();
                        setTimeout(() => {
                            bootstrap.Modal.getInstance(document.getElementById(config.modalId)).hide();
                        }, 1000);
                    } else {
                        utils.showMessage($(config.messageEl), result.message || '操作失败', 'danger');
                    }
                },
                error: function(xhr) {
                    const errorMessage = utils.handleApiError(xhr, '操作失败');
                    utils.showMessage($(config.messageEl), errorMessage, 'danger');
                }
            });
        });
    });
    
    // 确认删除
    $('#confirmDeleteBtn').on('click', function() {
        const deleteType = $('#deleteType').val();
        const deleteId = $('#deleteId').val();
        
        if (!deleteType || !deleteId) return;
        
        const deleteConfigs = {
            'student': { endpoint: `/students/${deleteId}`, reload: loadStudents },
            'course': { endpoint: `/courses/${deleteId}`, reload: loadCourses },
            'enrollment': { 
                endpoint: `/student-class?student_id=${deleteId.split('-')[0]}&class_id=${deleteId.split('-')[1]}`,
                reload: loadEnrollments
            }
        };
        
        const config = deleteConfigs[deleteType];
        if (!config) return;
        
        $.ajax({
            url: getFullApiPath(ROLE_API_PATHS[3], config.endpoint),
            type: 'DELETE',
            headers: utils.getAuthHeader(),
            success: function(response) {
                bootstrap.Modal.getInstance(document.getElementById('confirmDeleteModal')).hide();
                const result = utils.handleApiResponse(response);
                if (result.success) {
                    utils.showMessage($('#' + deleteType + 'Message'), '删除成功', 'success');
                    config.reload();
                    loadStatistics();
                } else {
                    utils.showMessage($('#' + deleteType + 'Message'), result.message || '删除失败', 'danger');
                }
            },
            error: function(xhr) {
                bootstrap.Modal.getInstance(document.getElementById('confirmDeleteModal')).hide();
                const errorMessage = utils.handleApiError(xhr, '删除失败');
                utils.showMessage($('#' + deleteType + 'Message'), errorMessage, 'danger');
            }
        });
    });
});

// 加载学生选项到下拉框
function loadStudentOptions() {
    $.ajax({
        url: getFullApiPath(ROLE_API_PATHS[3], '/students'),
        type: 'GET',
        headers: utils.getAuthHeader(),
        success: function(response) {
            const result = utils.handleApiResponse(response);
            const $select = $('#scStudentId');
            $select.empty().append('<option value="">请选择学生</option>');
            
            if (result.success && result.data) {
                result.data.forEach(student => {
                    $select.append(`<option value="${student.StudentID}">${student.StudentID} - ${student.Name}</option>`);
                });
            }
        }
    });
}

// 加载班级选项到下拉框
function loadClassOptions() {
    $.ajax({
        url: getFullApiPath(ROLE_API_PATHS[3], '/classes'),
        type: 'GET',
        headers: utils.getAuthHeader(),
        success: function(response) {
            const result = utils.handleApiResponse(response);
            const $select = $('#scClassId');
            $select.empty().append('<option value="">请选择教学班</option>');
            
            if (result.success && result.data) {
                result.data.forEach(cls => {
                    $select.append(`<option value="${cls.ClassID}">${cls.ClassID} - ${cls.CourseName} (${cls.TeacherName})</option>`);
                });
            }
        }
    });
}

// 统一的加载数据函数
function loadData(endpoint, tableId, columns, actions) {
    $.ajax({
        url: getFullApiPath(ROLE_API_PATHS[3], endpoint),
        type: 'GET',
        headers: utils.getAuthHeader(),
        success: function(response) {
            const result = utils.handleApiResponse(response);
            const $table = $(tableId);
            $table.empty();
            
            if (!result.success || !result.data.length) {
                $table.append(`<tr><td colspan="${columns.length}" class="text-center">暂无数据</td></tr>`);
                return;
            }
            
            result.data.forEach(item => {
                const row = columns.map(col => 
                    typeof col === 'function' ? col(item) : `<td>${item[col] || ''}</td>`
                ).join('');
                $table.append(`<tr>${row}${actions(item)}</tr>`);
            });
        }
    });
}

function loadStatistics() {
    loadData('/statistics', null, [], () => '');
    $.ajax({
        url: getFullApiPath(ROLE_API_PATHS[3], '/statistics'),
        type: 'GET',
        headers: utils.getAuthHeader(),
        success: function(response) {
            const result = utils.handleApiResponse(response);
            if (result.success && result.data) {
                const stats = result.data;
                $('#studentCount').text(stats.student_count || 0);
                $('#teacherCount').text(stats.teacher_count || 0);
                $('#courseCount').text(stats.course_count || 0);
                $('#classCount').text(stats.class_count || 0);
                $('#evaluationCount').text(stats.evaluation_count || 0);
                $('#averageScore').text(stats.average_score ? parseFloat(stats.average_score).toFixed(1) : '0.0');
            }
        }
    });
}

function loadStudents() {
    loadData('/students', '#studentList', 
        ['StudentID', 'Name', 'Major', () => '<td>学生</td>'],
        (student) => `<td><button class="btn btn-sm btn-danger" onclick="showDeleteConfirm('student', '${student.StudentID}', '学生: ${student.Name}')">删除</button></td>`
    );
}

function loadCourses() {
    loadData('/courses', '#courseList',
        ['CourseID', 'Name', 'Credit'],
        (course) => `<td><button class="btn btn-sm btn-danger" onclick="showDeleteConfirm('course', '${course.CourseID}', '课程: ${course.Name}')">删除</button></td>`
    );
}

function loadClasses() {
    loadData('/classes', '#classList',
        ['ClassID', 'CourseName', 'TeacherName', 'Semester', 'TimeLocation',
         (cls) => `<td>${cls.EvaluationCount || 0} / ${cls.AverageScore ? parseFloat(cls.AverageScore).toFixed(1) : '暂无'}</td>`],
        (cls) => `<td><button class="btn btn-sm btn-primary" onclick="showAddStudentToClassModal()">添加学生</button></td>`
    );
}

function loadEnrollments() {
    loadData('/enrollments', '#enrollmentList',
        ['StudentID', 'StudentName', 'ClassID', 'CourseName',
         (e) => `<td>${utils.formatDate(e.SelectTime)}</td>`,
         (e) => `<td>${e.HasEvaluated ? '<span class="badge bg-success">已评价</span>' : '<span class="badge bg-warning">未评价</span>'}</td>`],
        (e) => `<td><button class="btn btn-sm btn-danger" onclick="showDeleteConfirm('enrollment', '${e.StudentID}-${e.ClassID}', '选课记录')">删除</button></td>`
    );
}

function showAddStudentToClassModal() {
    new bootstrap.Modal(document.getElementById('addStudentClassModal')).show();
}

function showDeleteConfirm(type, id, name) {
    $('#deleteType').val(type);
    $('#deleteId').val(id);
    $('#deleteConfirmText').text(`确定要删除${name}吗？`);
    new bootstrap.Modal(document.getElementById('confirmDeleteModal')).show();
} 